<?php
namespace yan\jwt\utils;

class Rsa{
    public static function create($privateKeyFile=null, $publicKeyFile=null){
        // 配置密钥参数
        $config = array(
            "private_key_bits" => 2048,
            "private_key_type" => OPENSSL_KEYTYPE_RSA,
        );
        // 生成私钥资源
        $res = openssl_pkey_new($config);
        if($res===false){
            $err = [];
            while ($msg = openssl_error_string()) {
                $err[] = $msg;
            }
            throw new \Exception(implode(',', $err), 500);
        }
        // 导出私钥到变量
        \openssl_pkey_export($res, $privateKey);
        // echo "Private Key:\n" . $privateKey . "\n";

        // 导出公钥到变量
        $pubKeyDetails = openssl_pkey_get_details($res);
        $publicKey = $pubKeyDetails["key"];
        // echo "Public Key:\n" . $publicKey . "\n";

        if(!empty($privateKeyFile)){
            file_put_contents($privateKeyFile, $privateKey);
            // echo "Private Key saved to $privateKeyFile\n";
        }

        if(!empty($publicKeyFile)){
            file_put_contents($publicKeyFile, $publicKey);
            // echo "Public Key saved to $publicKeyFile\n";
        }
        return [
            'pri' => $privateKey,
            'pub' => $publicKey,
        ];
    }

    public static function encrypt($data, $publicKey, $flag=true){
        \openssl_public_encrypt($data, $encrypted, \openssl_pkey_get_public($publicKey));
        return $flag ? base64_encode($encrypted) : $encrypted;
    }

    public static function decrypt($data, $privateKey, $flag=true){
        \openssl_private_decrypt(($flag ? base64_decode($data) : $data), $decrypted, $privateKey); // 使用私钥解密
        return $decrypted; // 输出原始明文数据
    }
}